package com.snap.vseries.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.snap.vseries.Constants;
import com.snap.vseries.R;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.fragment.RunningIntensityFragment;
import com.snap.vseries.fragment.RunningMeltingFragment;
import com.snap.vseries.fragment.RunningProgramFragment;
import com.snap.vseries.fragment.RunningTempFragment;
import com.snap.vseries.service.ExpController;
import com.snap.vseries.service.PcrService;
import com.snap.vseries.service.OnExpStateChangedListener;
import com.snap.vseries.threadmanager.ThreadListener;
import com.snap.vseries.threadmanager.ThreadManger;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.ui.widget.ProgressBar;
import com.snap.vseries.ui.widget.TextButton;
import com.snap.vseries.utils.AutoUtil;
import com.snap.vseries.utils.TopTitleUtils;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 实验运行中：实验程序、温度曲线、荧光曲线
 */
public class ExpRunningActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    private final static String TAG = "ExpRunningActivity";
    private static final int MSG_RENDER = 99;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.container)
    FrameLayout container;
    @BindView(R.id.cl_drawer)
    ConstraintLayout clDrawer;
    @BindView(R.id.btn_drawer)
    TextButton btnDrawer;
    @BindView(R.id.start_time_tv)
    TextView startTimeTv;
    @BindView(R.id.plan_time_tv)
    TextView leftTimeTv;
    @BindView(R.id.end_time_tv)
    TextView endTimeTv;
    @BindView(R.id.current_temp_tv)
    TextView currentTempTv;
    @BindView(R.id.tv_process)
    TextView tvProcess;
    @BindView(R.id.progress_view)
    ProgressBar progressView;
    @BindView(R.id.radio1)
    RadioButton radio1;
    @BindView(R.id.radio2)
    RadioButton radio2;
    @BindView(R.id.radio3)
    RadioButton radio3;
    @BindView(R.id.no_wifi_warn_tv)
    TextView noWifiWarnTv;
    @BindView(R.id.not_connect_warn_tv)
    TextView notConnectWarnTv;

    private RadioButton[] radioButtons;
    private int currentCheckedId = -1;
    private RunningProgramFragment programFragment;
    private RunningTempFragment tempFragment;
    private RunningIntensityFragment ampFragment;
    private RunningMeltingFragment meltingFragment;
    private ExpInfo expInfo;
    public ExpController expController;
    private UiHandler renderHandler = new UiHandler(this);

    private OnExpStateChangedListener stateListener = new OnExpStateChangedListener() {
        @Override
        public void onStateChanged() {
            ExpRunningActivity.this.changeExpState(expController.getExpState());
        }
    };
    private ServiceConnection connection = new ServiceConnection() {

        @Override

        public void onServiceConnected(ComponentName name, IBinder service) {
            PcrService.PcrBinder binder = (PcrService.PcrBinder) service;
            mService=binder.getService();
            expController = mService.getCurrentController();
            mService.registerOnExpStateChangedListener(stateListener);
            onServiceBinded();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    private PcrService mService;


    private void changeExpState(int newState) {
        Log.e(TAG, "onStateChanged: newState :" + newState);
        runOnUiThread(() -> {
            if (newState == Constants.EXP_STATE_FINISH) {
                stopRender();
                showFinishDialog();
            } else if (newState == Constants.EXP_STATE_INTERRUPT) {
                stopRender();
                finish();
            }
        });
    }

    private void onServiceBinded() {
        expInfo = expController.getExpInfo();
        if (expInfo == null) {
            return;
        }
        renderHandler.obtainMessage(MSG_RENDER).sendToTarget();
        initProgramFragment();
        initView();
    }

    private void initProgramFragment() {
        if (programFragment != null) {
            Bundle bundle = expController.getRunSummary();
            if (bundle != null) {
                //开始时间点
                boolean isCurrentStageCycle = bundle.getBoolean("isCurrentStageCycle");
                int runningCycleInStage = bundle.getInt("runningCycleInStage");
                int runningTotalSection = bundle.getInt("runningTotalSection");
                programFragment.initProcess(runningTotalSection, runningCycleInStage, isCurrentStageCycle);
            }
        }
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_exp_running;
    }

    public void setExperimentProgress() {
        if (expController == null) {
            return;
        }
        if (expController.getExpState() == Constants.EXP_STATE_FINISH) {
            return;
        }
        Bundle bundle = expController.getRunSummary();
        if (bundle != null) {
            //开始时间点
            long beginTime = bundle.getLong("beginTime");
            startTimeTv.setText(AutoUtil.getHour(beginTime));
            //预计总运行时间
            long planTime = bundle.getLong("planTime");
            //预计剩余时间
            long leftTime = bundle.getLong("leftTime");
            //预计结束时间点
            endTimeTv.setText(AutoUtil.getHour(planTime + beginTime));
            //显示温度
            float currentTemp = bundle.getFloat("tecTemp");
            currentTempTv.setText(String.format("%s℃", currentTemp));
            if (beginTime != 0) {
                //剩余时间
                String left = AutoUtil.getHourAndMin(leftTime);
                leftTimeTv.setText(left);
                float percent = (System.currentTimeMillis() - beginTime) * 1f / planTime;
                if (percent >= 0) {
                    if (percent > 1) {
                        percent = 1;
                    }
                    tvProcess.setText(((int) (percent * 100)) + "%");
                    progressView.setProcess(percent);
                }
            }
        }

    }

    private void showFinishDialog() {
        new DialogView(this)
                .setTextContent("是否立即查看实验结果")
                .setTitle("实验已完成")
                .setCanceledOnTouchOutside(false)
                .setOnClickListener("确认", new DialogView.OnSureListener() {
                    @Override
                    public void onSureClick(String content) {
                        Intent intent = new Intent(ExpRunningActivity.this, ExpResultActivity.class);
                        if (!TextUtils.isEmpty(expInfo.getName()))
                            intent.putExtra("fileName", expInfo.getName());
                        startActivity(intent);
                        finish();
                    }
                })
                .setOnClickListener("取消", new DialogView.OnCancelListener() {
                    @Override
                    public void onCancelClick() {
                        finish();
                    }
                }).show();
    }


    private void initView() {
        radioButtons = new RadioButton[]{radio1, radio2, radio3};
        TextButton textView = new TextButton(this);
        textView.setText("终止");
        textView.setTextSize(16);
        textView.setTextColor(getResources().getColor(R.color.black666));
        textView.setClickable(false);

        new TopTitleUtils(this)
                .setTitle(expInfo.getName())
                .addRightView(textView)
                .setRightViewVisiable(View.VISIBLE)
                .setRight(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        stopExp();
                    }
                });
        radioGroup.check(R.id.radio1);
        initRadioButton(R.id.radio1);
        showFragment(R.id.radio1);
        radioGroup.setOnCheckedChangeListener(this);
    }

    private void stopExp() {
        final DialogView dialogView = new DialogView(this);
        dialogView.setTitle("终止实验");
        dialogView.setTextContent("终止后无法继续该实验，是否确认终止？");
        dialogView.setOnClickListener("仍然终止", new DialogView.OnSureListener() {
            @Override
            public void onSureClick(String content) {
                if (expController != null) {
                    ThreadManger.get().add(new ThreadListener() {
                        @Override
                        public void doAction() throws Exception {
                            expController.stopExp();
                        }
                    });
                }
            }
        }).show();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, PcrService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        if (expController != null) {
            mService.unregisterOnExpStateChangedListener(stateListener);
            expController = null;
            unbindService(connection);

        }
        super.onDestroy();
    }

    private void stopRender() {
        renderHandler.removeMessages(MSG_RENDER);
        if (tvProcess != null) {
            tvProcess.setText("100%");
            progressView.setProcess(1);
            //todo 停止当前页进度条
            if (tempFragment != null) {
                tempFragment.stopRender();
            }
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        showFragment(checkedId);
        initRadioButton(checkedId);
    }

    private void initRadioButton(int checkedId) {
        for (int i = 0; i < radioButtons.length; i++) {
            RadioButton radioButton = radioButtons[i];
            if (checkedId == radioButton.getId()) {
                radioButton.getPaint().setFakeBoldText(true);
            } else {
                radioButton.getPaint().setFakeBoldText(false);
            }
        }
    }

    private void showFragment(int checkedId) {
        if (currentCheckedId == checkedId) {
            return;
        }
        currentCheckedId = checkedId;

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        programFragment = (RunningProgramFragment) fm.findFragmentByTag(RunningProgramFragment.class.getSimpleName());
        tempFragment = (RunningTempFragment) fm.findFragmentByTag(RunningTempFragment.class.getSimpleName());
        ampFragment = (RunningIntensityFragment) fm.findFragmentByTag(RunningIntensityFragment.class.getSimpleName());

        hideAll(ft);

        switch (currentCheckedId) {
            case R.id.radio1:
                if (programFragment == null) {
                    programFragment = new RunningProgramFragment(expInfo);
                    ft.add(R.id.container, programFragment, RunningProgramFragment.class.getSimpleName());
                } else {
                    ft.show(programFragment);
                }
                break;
            case R.id.radio2:
                if (tempFragment == null) {
                    //测试数据
                    tempFragment = new RunningTempFragment(expInfo);
                    ft.add(R.id.container, tempFragment, RunningTempFragment.class.getSimpleName());
                } else {
                    ft.show(tempFragment);
                }
                break;
            case R.id.radio3:
                if (ampFragment == null) {
                    ampFragment = new RunningIntensityFragment(expInfo);
                    ft.add(R.id.container, ampFragment, RunningIntensityFragment.class.getSimpleName());
                } else {
                    ft.show(ampFragment);
                }
                break;
            case R.id.radio4:
                if (meltingFragment == null) {
                    meltingFragment = new RunningMeltingFragment(expInfo);
                    ft.add(R.id.container, meltingFragment, RunningMeltingFragment.class.getSimpleName());
                } else {
                    ft.show(meltingFragment);
                }
                break;
            default:
        }
        ft.commitAllowingStateLoss();
    }

    private void hideAll(FragmentTransaction ft) {
        if (programFragment != null) {
            ft.hide(programFragment);
        }
        if (tempFragment != null) {
            ft.hide(tempFragment);
        }
        if (ampFragment != null) {
            ft.hide(ampFragment);
        }
        if (meltingFragment != null) {
            ft.hide(meltingFragment);
        }
    }

    @OnClick({R.id.btn_drawer})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_drawer:
                if (clDrawer.getVisibility() == View.VISIBLE) {
                    btnDrawer.setBackground(getResources().getDrawable(R.drawable.ic_down));
                    clDrawer.setVisibility(View.GONE);
                } else {
                    btnDrawer.setBackground(getResources().getDrawable(R.drawable.ic_up));
                    clDrawer.setVisibility(View.VISIBLE);
                }
                if (programFragment != null) {
                    programFragment.initMargin(clDrawer.getVisibility() == View.VISIBLE);
                }
                break;
            default:
        }
    }

    /**
     * 每隔一秒钟更新进度条
     */
    private static class UiHandler extends Handler {
        private WeakReference<ExpRunningActivity> mActivity;

        private UiHandler(ExpRunningActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ExpRunningActivity activity = mActivity.get();
            if (activity != null) {
                if (msg.what == MSG_RENDER) {

                    activity.setExperimentProgress();

                    sendEmptyMessageDelayed(MSG_RENDER, 1000);
                }
            }
        }
    }

}
